package com.itlong.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.CloudControllerVO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.enumerate.CloudDeviceErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.equip.commons.ICloudElevatorServiceClient;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.equip.property.IDeviceCloudControllerServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.noncore.commons.IDeviceAlarmPushMessageServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.node.MapUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *      云端智能设备--云电梯接口控制器
 * </desc>
 *
 * @createDate 2017-11-15.
 */
@RestController
@RequestMapping("/smartCommunity/interface")
@RefreshScope
public class CloudElevatorController {
    private static final Logger LOG = LoggerFactory.getLogger(CloudElevatorController.class);

    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;
    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;
    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;
    @Autowired
    ICloudElevatorServiceClient iCloudElevatorServiceClient;
    @Autowired
    IDeviceCloudControllerServiceClient iDeviceCloudControllerServiceClient;
    @Autowired
    IDeviceAlarmPushMessageServiceClient iDeviceAlarmPushMessageServiceClient;





    /**
     * <desc>
     *      上报设备的能力集信息
     * </desc>
     *
     * @param token
     * @param capacitySet 表示设备支持哪些功能，有哪些能力 json String数据
     * @return
     * @author Jiaqi.X
     * @createDate 2018/03/29
     *
     */
    @RequestMapping(path="/device/elevator/reportCapacitySet")
    @ResponseBody
    public Object reportCapacitySet(String deviceType,String token,String capacitySet,HttpServletRequest request){
        try{
            if(StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                token = params.get("token").toString();
                capacitySet = JsonUtil.toJSON(params.get("capacitySet"));
                deviceType =  params.get("deviceType").toString();
            }
            if(StringUtils.isBlank(capacitySet)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_ELEVATOR_PROP_NULL_ERROR.getErrorCode());
            }

            LOG.info("【电梯能力集上报】{} {}", deviceType, capacitySet);

            if ("128".equals(deviceType)) {
                //群控器
                CloudControllerVO cluster = iDeviceCloudControllerServiceClient.retrieve(token);
                iDeviceCloudControllerServiceClient.reportCapacitySet(cluster.getDeviceUnique(),
                        cluster.getIotProductKey()==null?"":cluster.getIotProductKey(),capacitySet);
            }else {
                //云电梯
                CloudElevatorVO elevator = iCloudElevatorServiceClient.retrieve(token);
                iCloudElevatorServiceClient.reportCapacitySet(elevator.getDeviceUnique(),elevator.getIotProductKey()==null?"":elevator.getIotProductKey(),capacitySet);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【云电梯/群控器】上报设备的能力集信息失败", e);
        }
    }

    /**
     * <desc>
     *      获取设备固定密码
     * </desc>
     *
     * @param dto 云电梯分页dto类
     * @return
     * @author Jiaqi.X
     * @createDate 2018/03/30
     */
    @RequestMapping(path = "/device/elevator/pullDevicePwd")
    @ResponseBody
    public Object pullDevicePwd(CloudElevatorPageDTO dto,HttpServletRequest request){
        try{
            if(dto.getToken() == null){
                Map<String,Object> params = request.getAttribute("params") != null ? (HashMap)request.getAttribute("params") : null;
                if(params != null) {
                    dto = (CloudElevatorPageDTO) MapUtil.mapToObject(params, CloudElevatorPageDTO.class);
                }
            }

            if(StringUtils.isBlank(dto.getSn())){
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if(dto.getPage() == null || dto.getPageSize() == null){
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PAGE_ERROR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iCloudElevatorServiceClient.pullDevicePwd(dto));
        }catch (Exception e){
            throw new DataAccessException("【云电梯】获取设备固定密码失败", e);
        }
    }

    /**
     * <desc>
     *      获取设备所有者的认证信息
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Qiang.S
     * @createDate 2019-04-25
     */
    @RequestMapping(value = "/device/elevator/pullDeviceAuthInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullDeviceAuthInfo(CloudIntercomDeviceAuthGetDTO getDTO, HttpServletRequest request){
        String elapsedtime = "【pullDeviceAuthInfo云电梯设备所有者的认证信息】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            if(getDTO.getToken() == null){
                Map<String,Object> params = request.getAttribute("params") != null ? (HashMap)request.getAttribute("params") : null;
                if(params != null) {
                    getDTO = JsonUtil.decode(JsonUtil.toJSON(params), new TypeReference<CloudIntercomDeviceAuthGetDTO>() {});
                }
            }
            //合法性判断
            if (null == getDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(getDTO.getSn())){
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            elapsedtime += ";getDeviceServeRoomsByPage开始执行：" + DateUtil.fomatDate1(new Date());
            //获取服务的房间列表及其住户信息
            Page<CloudElevatorDeviceAuthVO.Room> roomPage =
                    iCloudElevatorServiceClient.getDeviceServeRoomsByPage(getDTO);

            elapsedtime += ";getUsersByRoomIds开始执行：" + DateUtil.fomatDate1(new Date());
            if (null != roomPage && roomPage.getRows() != null&&roomPage.getRows().size()>0){
                List<String> roomIds = new ArrayList<>();
                for (int i = 0; i< roomPage.getRows().size(); i++){
                    roomIds.add(roomPage.getRows().get(i).getRoomId());
                    //每50个房间获取一次
                    if (roomIds.size() == 50){
                        List<CloudElevatorDeviceAuthVO.RoomUser> users =
                                iCloudElevatorServiceClient.getUsersByRoomIds(StringUtils.join(roomIds,','));
                        if (users != null && !users.isEmpty()){
                            users.forEach(usr->{
                                for (int j=0; j < roomPage.getRows().size(); j++){
                                    CloudElevatorDeviceAuthVO.Room room = roomPage.getRows().get(j);
                                    if (room.getRoomId().equals(usr.getRoomId())){
                                        if (room.getRoomUserArr() == null){
                                            room.setRoomUserArr(new ArrayList<>());
                                            room.getRoomUserArr().add(usr);
                                        }else {
                                            room.getRoomUserArr().add(usr);
                                        }
                                    }
                                }
                            });
                        }
                        roomIds.clear();
                    }
                }
                if (!roomIds.isEmpty()){
                    List<CloudElevatorDeviceAuthVO.RoomUser> users =
                            iCloudElevatorServiceClient.getUsersByRoomIds(StringUtils.join(roomIds,','));
                    if (users != null && !users.isEmpty()){
                        users.forEach(usr->{
                            for (int j=0; j < roomPage.getRows().size(); j++){
                                CloudElevatorDeviceAuthVO.Room room = roomPage.getRows().get(j);
                                if (room.getRoomId().equals(usr.getRoomId())){
                                    if (room.getRoomUserArr() == null){
                                        room.setRoomUserArr(new ArrayList<>());
                                        room.getRoomUserArr().add(usr);
                                    }else {
                                        room.getRoomUserArr().add(usr);
                                    }
                                }
                            }
                        });
                    }
                }
            }

            CloudElevatorDeviceAuthVO deviceAuthVO = new CloudElevatorDeviceAuthVO();
            deviceAuthVO.setDeviceAuthArr(roomPage.getRows());
            deviceAuthVO.setCurrentTotal(roomPage.getRows().size());
            deviceAuthVO.setTotal(roomPage.getPage().getTotalNumber());
            deviceAuthVO.setPage(roomPage.getPage().getCurrentPage());
            deviceAuthVO.setHaveNext(roomPage.getPage().getTotalPage() -
                    roomPage.getPage().getCurrentPage() > 0 ? 1 : 0);

            //最后一页并且需要访客信息的时候
            if (deviceAuthVO.getHaveNext() == 0) {
                SimpleDateFormat sdf =new SimpleDateFormat("yyMMddHHmmss");
                SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //拼接访客信息
                List<CloudElevatorDeviceAuthVO.Room> deviceAuthArr = roomPage.getRows();
                //查询该设备访客下的信息
                List<CloudIntercomVisitorVO> list = iCloudElevatorServiceClient.getVisitorInfoByUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(getDTO.getSn()));
                for (CloudIntercomVisitorVO vo : list) {
                    CloudElevatorDeviceAuthVO.Room room = new CloudElevatorDeviceAuthVO.Room();
                    CloudElevatorDeviceAuthVO.RoomUser roomUser = new CloudElevatorDeviceAuthVO.RoomUser();
                    List<CloudElevatorDeviceAuthVO.RoomUser> listRoomUser = new ArrayList<>();
                    roomUser.setUserId(vo.getVFaceId() == null ? "" : vo.getVFaceId());
                    Date date =sdf2.parse(vo.getStartTime());
                    roomUser.setStartTime(sdf.format(date));
                    date =sdf2.parse(vo.getEndTime());
                    roomUser.setEndTime(sdf.format(date));
                    roomUser.setRoomId(vo.getRoomId());
                    roomUser.setVisitorType(1);
                    roomUser.setUserName(vo.getVisitorName() == null ? "" : vo.getVisitorName());
                    roomUser.setIdcardKey(vo.getIdcardKey() == null ? "" : vo.getIdcardKey());
                    room.setRoomId(vo.getRoomId());
                    room.setRoomNum(vo.getRoomNum());
                    room.setStatus(vo.getRoomStatus());
                    room.setLiftDoorType(vo.getLiftDoorType());
                    room.setSoftCardNums(vo.getSoftCardNums() == null ? "" : vo.getSoftCardNums());
                    room.setArrearsTime(vo.getArrearsTime());
                    room.setOpenPwd(vo.getOpenPwd() == null ? "" : vo.getOpenPwd());

                    listRoomUser.add(roomUser);
                    room.setRoomUserArr(listRoomUser);
                    deviceAuthArr.add(room);
                }
            }
            return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), deviceAuthVO);
        }catch (Exception e){
            throw new DataAccessException("【云电梯】获取设备所有者的认证信息失败", e);
        }finally {
            elapsedtime += ";【pullDeviceAuthInfo获取设备所有者的认证信息】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     *      校验用户信息（目前获取用户或卡号所在房间的通行所剩次数）
     * </desc>
     *
     * @param dto 校验用户信息dto类
     * @return
     * @author Juguang.S
     * @createDate 2020/12/25
     */
    @RequestMapping(path = "/device/checkUserInfo")
    @ResponseBody
    public Object checkUserInfo(CloudDeviceCheckUserInfoDTO dto, HttpServletRequest request){
        try{
            if(dto.getToken() == null){
                Map<String,Object> params = request.getAttribute("params") != null ? (HashMap)request.getAttribute("params") : null;
                if(params != null) {
                    dto = JsonUtil.toObject(JsonUtil.toJSON(params),CloudDeviceCheckUserInfoDTO.class);
                }
            }else{
                Map<String,Object> params = request.getAttribute("params") != null ? (HashMap)request.getAttribute("params") : null;
                dto = JsonUtil.toObject(JsonUtil.toJSON(params),CloudDeviceCheckUserInfoDTO.class);
            }

            if(StringUtils.isBlank(dto.getSn())){
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            Integer count = iCloudElevatorServiceClient.checkUserInfo(dto);
            Map<String,Integer> map = new HashMap<>();
            map.put("balance",count);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        }catch (Exception e){
            throw new DataAccessException("【云电梯】校验用户信息失败", e);
        }
    }

    /**
     * <desc>
     *      上报告警事件
     * </desc>
     *
     * @param token
     * @param deviceEventArr 告警事件 对象数组
     * @return
     * @author Juguang.S
     * @createDate 2021/05/28
     *
     */
    @ResponseBody
    @RequestMapping(path="/device/pushAlarmEvent")
    public Object pushAlarmEvent(String sn,String deviceType,String token,String deviceEventArr,HttpServletRequest request){
        try{
            if(StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                token = params.get("token").toString();
                deviceEventArr = JsonUtil.toJSON(params.get("deviceEventArr"));
                deviceType =  params.get("deviceType").toString();
                sn =  params.get("sn").toString();
            }
            if(StringUtils.isBlank(deviceEventArr)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_ELEVATOR_PUSH_ALARM_NULL_ERROR.getErrorCode());
            }
            List<CloudElevatorAlarmInfoDTO> alarms;
            boolean remark = false;
            String eventSeq = "";
            try {
                deviceEventArr = StringEscapeUtils.unescapeJava(deviceEventArr.substring(1,deviceEventArr.length()-1));
                alarms =  JsonUtil.decode(deviceEventArr, new TypeReference<List<CloudElevatorAlarmInfoDTO>>() {});
                for(CloudElevatorAlarmInfoDTO alarmInfoDTO : alarms){
                    if(StringUtils.isNotBlank(alarmInfoDTO.getImage())){
                        alarmInfoDTO.setImage(alarmInfoDTO.getImage().replaceAll(" ","+"));
                    }
                    if(StringUtils.isNotBlank(alarmInfoDTO.getEventSeq())){
                        eventSeq = alarmInfoDTO.getEventSeq();
                        remark = true;
                    }
                }
                //LOG.info("【告警事件】："+"当前时间"+DateUtil.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss:")+alarms.get(0).getEventSeq());
            } catch (IOException e) {
                throw new Exception("pushAlarmEvent【云端接收设备端上报告警事件】解析告警事件json失败", e);
            }

            iCloudElevatorServiceClient.pushAlarmEvent(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn),alarms);
            iDeviceAlarmPushMessageServiceClient.deviceAlarmPushMessage(StringHandlerUtil.getProjectIdBySn(sn),remark,eventSeq);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【云电梯】上报告警事件失败", e);
        }
    }
}
